package com.example.xiaojian.myokhttp3;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetRequestActivity extends AppCompatActivity {

    private Button simpleGetBtn ;
    private Button addParamGetBtn;
    private TextView result_textview;
    private OkHttpClient okHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_request);
        setTitle("Get请求的用法");

        simpleGetBtn  = (Button) findViewById(R.id.simpleGetBtn);
        addParamGetBtn = (Button) findViewById(R.id.addParamGetBtn);
        result_textview = (TextView) findViewById(R.id.resultTextview);

        okHttpClient = new OkHttpClient();

        simpleGetBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Request request = new Request.Builder()
                        .url("http://www.baidu.com")
                        .build();
                okHttpClient.newCall(request).enqueue(callback);
            }
        });

        addParamGetBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Request request = new Request.Builder()
                        .addHeader("token","2123431543654676587")
                        .url("http://www.baidu.com")
                        .build();
                okHttpClient.newCall(request).enqueue(callback);
            }
        });



    }

    private Callback callback = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            setResult(e.getMessage(),false);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            setResult(response.body().string(),true);
        }
    };

    public void setResult(final String msg,final boolean flag){
        GetRequestActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(flag){
                    Toast.makeText(GetRequestActivity.this, "请求成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(GetRequestActivity.this,"请求失败",Toast.LENGTH_SHORT).show();
                }
                result_textview.setText(msg);
            }
        });
    }


}
